<template>
  <div>
    <el-row class="row_box">
      <el-col :span="15" :offset="2">
        <div class="title" @click="toHome">小新零食商城</div>
      </el-col>
      <el-col :span="3" style="width:300px !important;">
        <el-menu
          :default-active="activeIndex"
          mode="horizontal"
          @select="handleSelect"
          background-color="bisque"
          text-color="#131311"
          active-text-color="#e25660"
        >
          <el-menu-item index="home" style="font-size: 20px !important;font-weight: bold !important;">商城&nbsp;&nbsp;&nbsp;&nbsp;</el-menu-item>
          <el-menu-item index="shoppingCart" style="font-size: 20px !important;font-weight: bold !important;">购物车</el-menu-item>
        </el-menu>
      </el-col>
      <el-col :span="2">
        <el-dropdown @command="handleDownBoxCommand">
          <span class="el-dropdown-link">
            {{ username }}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "Header",
  data() {
    return {
      activeIndex: "home",
    };
  },
  computed: {
    ...mapState({
      username: (state) => state.username,
    }),
  },
  methods: {
    handleSelect(key) {
      const pathMap = {
        home: "/home",
        shoppingCart: "/shoppingCart",
      };
      const targetPath = pathMap[key];
      if (this.$route.path !== targetPath) {
        this.$router.push(targetPath);
      }
    },
    logout() {
      this.$message({
        type: "success",
        message: "退出成功",
      });
      this.$router.push("/welcome");
    },
    toHome() {
      if (this.$route.path !== "/home") {
        this.$router.push("/home");
      }
    },
    handleDownBoxCommand(command) {
      if (command === "logout") {
        this.logout();
      }
    },
  },
  watch: {
    $route(to, from) {
      if (to.name === "Home") {
        this.activeIndex = "home";
      } else if (to.name === "ShoppingCart") {
        this.activeIndex = "shoppingCart";
      } else {
        this.activeIndex = "";
      }
    },
  },
};
</script>

<style scoped>
.row_box {
  background-color: bisque;
}
.title {
  letter-spacing: 2px;
  font-size: 35px;
  color: #fdf6f6;
  float: left;
  font-weight: 600;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  line-height: 65px;
  cursor: pointer; /* 添加鼠标悬停样式 */
}
.el-dropdown-link {
  cursor: pointer;
  color: #141112;
  font-size: 20px;
  line-height: 62px;
}
.el-icon-arrow-down {
  font-size: 20px;
}
</style>